package com.peking.donations.base.util;

import com.peking.donations.base.security.LoggedUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.provider.OAuth2Authentication;


public class SecurityUtil {
    /**
     * 从安全上下文中取得当前登录的用户 如果没有取到会返回null
     * 
     * @return
     */
    public static LoggedUser getCurrentUser() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        if (auth != null) {
//            if (auth.getName().equals("anonymous")) {
//                return null;
//            }
            if(auth instanceof OAuth2Authentication){
                OAuth2Authentication oAuth2Authentication= (OAuth2Authentication) auth;
                if(oAuth2Authentication.getUserAuthentication().getDetails() instanceof LoggedUser){
                    return (LoggedUser) oAuth2Authentication.getUserAuthentication().getDetails();
                }
            }
            if (auth.getDetails() instanceof LoggedUser) {
                return (LoggedUser) auth.getDetails();
            }
            if (auth.getPrincipal() instanceof LoggedUser) {
                return (LoggedUser) auth.getPrincipal();
            }

            if (auth.getPrincipal() instanceof User) {
                User user = (User) auth.getPrincipal();
                LoggedUser loggedUser = new LoggedUser(user.getUsername(), user.getAuthorities());
                return loggedUser;
            }
        }
        return null;
    }
}
